package com.sj.mbt.ui.machine.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.sj.mbt.R;
import com.sj.mbt.ui.adapter.MachineListNewAdapter;
import com.sj.mbt.ui.machine.AddMachineActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.rongcloud.im.server.network.http.HttpException;
import cn.rongcloud.im.server.response.MachineUserListResponse;
import cn.rongcloud.im.server.utils.NToast;
import cn.rongcloud.im.ui.fragment.base.BaseFragment;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MachineFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MachineFragment extends BaseFragment implements MachineListNewAdapter.OnOpenItemClickListener, MachineListNewAdapter.OnCloseItemClickListener, MachineListNewAdapter.OnAddItemClickListener {

    private static final int MACHINE_USER_BY_PAGE = 1;
    private static final int GET_USER = 2;
    private static final int COIN_COUNT_BY_USER = 3;
    private static final int COIN_LIST = 4;
    private static final int MACHINE_OPEN = 5;
    private static final int MACHINE_CLOSE = 6;

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String ARG_TITLE = "title";

    @BindView(R.id.recycle_view)
    RecyclerView recycleView;
    Unbinder unbinder;

    private String mParam1;
    private String mParam2;

    private int pageNum = 1;
    private int pageSize = 20;
    private MachineListNewAdapter adapter;
    private String machineId;

    private OnFragmentInteractionListener mListener;
    private String mTitles;

    public MachineFragment() {
        // Required empty public constructor
    }

    public static MachineFragment getInstance(String title) {
        MachineFragment fra = new MachineFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_TITLE, title);
        fra.setArguments(bundle);
        return fra;
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MachineFragment.
     */
    public static MachineFragment newInstance(String param1, String param2) {
        MachineFragment fragment = new MachineFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
            mTitles = getArguments().getString(ARG_TITLE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_machine, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    private void initView() {
        adapter = new MachineListNewAdapter(mContext);
        adapter.setOnOpenItemClickListener(this);
        adapter.setOnCloseItemClickListener(this);
        adapter.setOnAddItemClickListener(this);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    public void setData(List<MachineUserListResponse.DataBean> data) {
        List<MachineUserListResponse.DataBean> dataBeanList = data;
        if (adapter != null && dataBeanList != null) {
            List<MachineUserListResponse.DataBean> dataBeen = new ArrayList<>();
            for (MachineUserListResponse.DataBean bean :
                    dataBeanList) {
                if (getLevel(mTitles,bean.getLevel())){
                    dataBeen.add(bean);
                }
            }
            adapter.setDataList(dataBeen);
            recycleView.setAdapter(adapter);
            if (!TextUtils.isEmpty(mTitles) && "高级".equals(mTitles))
                recycleView.setLayoutManager(new GridLayoutManager(mContext, 2));
            else
                recycleView.setLayoutManager(new GridLayoutManager(mContext, 3));
            adapter.notifyDataSetChanged();
        }
    }

    /**
     *
     * @param mTitles
     * @param level     矿机级别 5201 迷你 5202 初级 5203 中级 5204 高级
     * @return
     */
    private boolean getLevel(String mTitles, int level) {
        if (mTitles.equals("迷你")){
            return "5201".equals(level+"");
        }else if (mTitles.equals("初级")){
            return "5202".equals(level+"");
        }else if (mTitles.equals("中级")){
            return "5203".equals(level+"");
        }else if (mTitles.equals("高级")){
            return "5204".equals(level+"");
        }
        return false;
    }


    @Override
    public Object doInBackground(int requestCode, String id) throws HttpException {
        switch (requestCode) {
            case MACHINE_USER_BY_PAGE:
                return action.listMachineUserByPage(pageNum + "", pageSize + "");
            case GET_USER:
                return action.getUser();
            case COIN_LIST:
                return action.coinList();
            case MACHINE_OPEN:
                return action.machineOpen(machineId);
            case MACHINE_CLOSE:
                return action.machineClose(machineId);
        }
        return super.doInBackground(requestCode, id);
    }

    @Override
    public void onSuccess(int requestCode, Object result) {
        if (result != null) {
            switch (requestCode) {
                case MACHINE_USER_BY_PAGE:
                    MachineUserListResponse scrres = (MachineUserListResponse) result;
                    if (scrres.getResultCode() == 0) {

                    } else {
                        NToast.shortToast(mContext, scrres.getMsg());
                    }
                    break;
            }
        }
    }

    @Override
    public void onFailure(int requestCode, int state, Object result) {
        switch (requestCode) {
            case MACHINE_USER_BY_PAGE:
                NToast.shortToast(mContext, "请求失败！");
                break;
        }
    }

    @Override
    public void onOpenItemClick(ImageView v, int position, MachineUserListResponse.DataBean data) {
        machineId = data.getMuid() + "";
        request(MACHINE_OPEN);
    }

    @Override
    public void onCloseItemClick(ImageView v, int position, MachineUserListResponse.DataBean data) {
        machineId = data.getMuid() + "";
        request(MACHINE_CLOSE);
    }

    @Override
    public void onAddItemClick(View v, int position, MachineUserListResponse.DataBean data) {
        startActivityForResult(new Intent(getActivity(), AddMachineActivity.class), 10);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        onButtonPressed(null);
    }
}
